import Router from '@koa/router'
import { postLoginService } from '../services/login'
import {
    insert,
    like,
    select,
    delete as sqlDelete,
    update,
    eq,
} from 'mysql-bricks'
import { query } from '../models'

/**
 * 登录
 * @param ctx.body.username 用户名
 * @param ctx.body.password 密码
 * @returns 返回token
 */
export const postLogin: Router.Middleware = async (ctx) => {
    const { type, username, password } = ctx.request.body

    const from = type === 0 ? 'user' : 'owner'
    const usernameProp = type === 0 ? 'username' : 'phone'
    const sql = select()
        .from(from)
        .where({
            [usernameProp]: username,
            password,
        })
        .toString()
    console.log(sql)

    const res = (await query(sql)) as any

    console.log(res)
    if (res.length === 0) {
        ctx.status = 401
        ctx.body = {
            data: null,
            msg: '用户名或密码错误',
        }
        return
    }

    // 返回数据
    ctx.body = {
        type,
        username,
        name: res[0].name,
        id: res[0].id,
        expireTime: res[0].expireTime,
    }
}
